package com.tzt.jpush;

import java.util.Map;

import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.audience.Audience;
import com.tzt.contents.ErrorCodeConstant;
import com.tzt.exception.InnerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tzt.util.GetCacheUtil;
import com.tzt.util.JsonUtil;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;

@Service
public class JpushMessageService
{
    /**
     * 保存离线的时长。秒为单位。最多支持10天（864000秒）。 0 表示该消息不保存离线。即：用户在线马上发出，当前不在线用户将不会收到此消息。
     * 此参数不设置则表示默认，默认为保存1天的离线消息（86400秒)。
     */
    private static long timeToLive = 60 * 60 * 24;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private GetCacheUtil getCacheUtil;

    @SuppressWarnings("deprecation")
    public boolean sendPush(PushPayload payload)
    {
        Map<String, String> jpushInfo = getCacheUtil.getJpushInfo();
        JPushClient jPushClient = new JPushClient(jpushInfo.get("masterSecret"), jpushInfo.get("appKey"),
                (int) timeToLive);
        boolean flag = false;
        try
        {
            System.out.println("构造数据：" + payload.toString());
            PushResult result = jPushClient.sendPush(payload);
            if (null != result)
            {
                logger.info("Get resul ---" + result);
                flag = true;
            }
        }
        catch (APIConnectionException e)
        {
            logger.error("Connection error. Should retry later. ", e);
            flag = false;
        }
        catch (APIRequestException e)
        {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
            logger.info("Msg ID: " + e.getMsgId());
            flag = false;
        }
        return flag;

    }

    public PushResult sendPush(Map<String, Object> map, String alias) throws Exception
    {
        try
        {
            logger.info("极光推送： map" + map.toString() + " <==> alias:" + alias);
            Map<String, String> jpushInfo = getCacheUtil.getJpushInfo();
            JPushClient jPushClient = new JPushClient(jpushInfo.get("masterSecret"), jpushInfo.get("appKey"), null,
                    ClientConfig.getInstance());
            PushPayload payload = JPushUtil.buildPushObject_all_alias_alert(alias, JsonUtil.convertMapToJson(map));
            PushResult result = jPushClient.sendPush(payload);
            logger.info("Got result - " + result);
            logger.info("极光推送成功：openMap" + map.toString() + " <==> alias:" + alias);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            throw new InnerException(ErrorCodeConstant.FAILED, "极光推送失败！");
        }

    }


}